<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Queue;

/**
 * 招聘管理
 *
 * @icon fa fa-circle-o
 */
class Job extends Backend
{

    /**
     * Job模型对象
     * @var \app\admin\model\Job
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Job;
        $this->view->assign("jobIsGroupList", $this->model->getJobIsGroupList());
        $this->view->assign("jobTypeList", $this->model->getJobTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['hotel', 'company', 'usergroup', 'area'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('hotel')->visible(['hotel_name']);
                $row->getRelation('area')->visible(['name']);
                $row->getRelation('company')->visible(['company_name']);
                $row->getRelation('usergroup')->visible(['company_name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 验证上岗时间
                if (strtotime($params['job_arrival_datetime']) < time()) {
                    $this->error('上岗时间不能是过去的时间');
                }
                if (strtotime($params['job_arrival_datetime']) < time() + 1800) {
                    $this->error('上岗时间必须比现在的时间多30分钟');
                }

                // 验证是否分组
                if ($params['job_is_group'] == 1) {
                    $params['job_company_group_id'] == 0 && $this->error('缺少用户分组');
                } else {
                    unset($params['job_company_group_id']);
                }

                // 验证是否自定义班别
                if ($params['job_type'] == 4) {
                    empty($params['job_top_start']) && $this->error('缺少上午开始时间');
                    empty($params['job_top_end']) && $this->error('缺少上午结束时间');
                    empty($params['job_down_start']) && $this->error('缺少下午开始时间');
                    empty($params['job_down_end']) && $this->error('缺少下午结束时间');
                } else {
                    unset($params['job_top_start']);
                    unset($params['job_top_end']);
                    unset($params['job_down_start']);
                    unset($params['job_down_end']);
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {

                    $data = ['id' => $this->model->getData('id'), 'queue_update' => 1];
                    /**
                     * 定时将招聘改为进行中
                     */
                    // 上岗时间前10分钟
                    $time = strtotime($params['job_arrival_datetime']) - 600 - strtotime('now');
                    // 队列
                    $QueueRes = Queue::later($time, 'app\common\queue\Start', $data, 'job_start');
                    if ($QueueRes !== 1) {
                        $this->error('定时任务发布失败');
                    }

                    /**
                     * 定时判断订单异常还是结算
                     */
                    // 上岗时间+工作时间+6小时 自动结算
                    $time = strtotime($params['job_arrival_datetime']) + $params['job_time_hour'] * 3600 + 6 * 3600 - strtotime('now');
                    // 队列
                    $QueueResult = Queue::later($time, 'app\common\queue\End', $data, 'job_end');
                    if ($QueueResult !== 1) {
                        $this->error('定时任务发布失败');
                    }

                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                // 验证上岗时间
                if (strtotime($params['job_arrival_datetime']) < time()) {
                    $this->error('上岗时间不能是过去的时间');
                }
                if (strtotime($params['job_arrival_datetime']) < time() + 1800) {
                    $this->error('上岗时间必须比现在的时间多30分钟');
                }

                // 验证是否分组
                if ($params['job_is_group'] == 1) {
                    $params['job_company_group_id'] == 0 && $this->error('缺少用户分组');
                } else {
                    unset($params['job_company_group_id']);
                }

                // 验证是否自定义班别
                if ($params['job_type'] == 4) {
                    empty($params['job_top_start']) && $this->error('缺少上午开始时间');
                    empty($params['job_top_end']) && $this->error('缺少上午结束时间');
                    empty($params['job_down_start']) && $this->error('缺少下午开始时间');
                    empty($params['job_down_end']) && $this->error('缺少下午结束时间');
                } else {
                    unset($params['job_top_start']);
                    unset($params['job_top_end']);
                    unset($params['job_down_start']);
                    unset($params['job_down_end']);
                }

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $row->setInc('queue_update');
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $data = ['id' => $ids, 'queue_update' => $row->getData('queue_update')];

                    /**
                     * 定时将招聘改为进行中
                     */
                    // 上岗时间前10分钟
                    $time = strtotime($params['job_arrival_datetime']) - 600 - strtotime('now');
                    // 队列
                    $QueueRes = Queue::later($time, 'app\common\queue\Start', $data, 'job_start');
                    if ($QueueRes !== 1) {
                        $this->error('定时任务发布失败');
                    }

                    /**
                     * 定时判断订单异常还是结算
                     */
                    // 上岗时间+工作时间+6小时 自动结算
                    $time = strtotime($params['job_arrival_datetime']) + $params['job_time_hour'] * 3600 + 6 * 3600 - strtotime('now');
                    // 队列
                    $QueueResult = Queue::later($time, 'app\common\queue\End', $data, 'job_end');
                    if ($QueueResult !== 1) {
                        $this->error('定时任务发布失败');
                    }

                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 发布
     */
    public function release()
    {
        $id = input('ids', false);
        if (!$id) $this->error('参数错误');

        $row = $this->model->get($id);
        try {
            Db::startTrans();
            $result = $row->save(['status' => 2], ['id' => $id]);
            if (!$result) {
                throw new Exception('未发生更改');
            }
            Db::commit();
            $this->success('发布成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 下线
     */
    public function offline()
    {
        $id = input('ids', false);
        if (!$id) $this->error('参数错误');

        $row = $this->model->get($id);
        try {
            Db::startTrans();
            $result = $row->save(['status' => 5], ['id' => $id]);
            if (!$result) {
                throw new Exception('未发生更改');
            }
            Db::commit();
            $this->success('下线成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 查看
     */
    public function view()
    {
        $id = input('ids', false);
        if (!$id) $this->error('参数错误');

        $row = $this->model->with(['hotel', 'company', 'usergroup'])->find($id);

        $row->getRelation('hotel')->visible(['hotel_name']);
        $row->getRelation('company')->visible(['company_name']);
        $row->getRelation('usergroup')->visible(['company_name']);

        if ($row) {
            $this->assign('row', $row);
            return $this->fetch('view');
        }
        $this->error('数据未找到');
    }

    /**
     * 批量发布/下线
     */
    public function batch()
    {
        $id  = input('ids', false);
        $act = input('act', false);

        if (!$id) $this->error('参数错误');
        if (!$act) $this->error('参数错误');

        try {
            Db::startTrans();
            $result = $this->model->save(['status' => $act], ['id' => ['in', $id]]);

            if (!$result) {
                throw new Exception('未发生更改');
            }
            Db::commit();
            $this->success('操作成功');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

}
